package com.qingzhuge.dao.id;

import com.qingzhuge.context.SpringContext;
import com.qingzhuge.id.SnowflakeId;
import com.qingzhuge.autoconfigure.QingTingProperties;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

/**
 * @author : zero.xiao
 * @description : 生成id的方法
 * @date :2019/1/4 0004 下午 14:39
 * @since : 1.0.0
 * @modified :
 */
public abstract class BaseIdGenerate implements IdentifierGenerator {
    private SnowflakeId snowflakeId;
    /**
     * hibernate自定义主键生成规则必须实现 IdentifierGenerator  generate 为默认方法
     */
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        if (null == snowflakeId) {
            synchronized (BaseIdGenerate.class) {
                if (null == snowflakeId) {
                    QingTingProperties qingTingProperties = SpringContext.getBean(QingTingProperties.class);
                    snowflakeId = new SnowflakeId(
                            qingTingProperties.getDataSource().getWorid(),
                            qingTingProperties.getDataSource().getDataid());
                }
            }
        }
        return getId(snowflakeId);
    }

    /**
     * 获取id
     * @param snowflakeId 雪花算法类
     * @return id
     */
    protected abstract Serializable getId(SnowflakeId snowflakeId);
}